axios.defaults.baseURL = "https://apifoxmock.com/m1/4733523-4386118-default";  

  
function showToast(msg) {  
    const toastDom = document.querySelector(".my-toast");  
    if (!toastDom) return; // 确保元素存在  
    const toast = new bootstrap.Toast(toastDom);  
    document.querySelector(".toast-body").innerHTML = msg;  
    toast.show();  
}  
  
function checkLogin() {  
    const token = localStorage.getItem("token");  
    if (!token) {  
        showToast("非法访问，请先登录");  
        setTimeout(() => {  
            location.href = "./login.html";  
        }, 1500);  
    }  
}  
  
function renderUsername() {  
    const username = localStorage.getItem("username");  
    const usernameElem = document.querySelector(".username");  
    if (usernameElem) { // 确保元素存在  
        usernameElem.innerHTML = username;  
    }  
}  
  
function registerLoginOut() {  
    document.querySelector("#logout").addEventListener("click", () => {  
        localStorage.removeItem("username");  
        localStorage.removeItem("token");  
        location.href = "./login.html";  
    });  
}  
  
// axios 拦截器 请求/响应  
axios.interceptors.request.use(  
    function (config) {  
        config.headers["info"] = "hi";  
        console.log(config);  
        const token = localStorage.getItem("token");  
        if (token) {  
            config.headers["Authorization"] = token;  
        }  
        return config;  
    },  
    function (error) {  
        return Promise.reject(error);  
    }  
);  
  
axios.interceptors.response.use(  
    function (response) {  
        return response;  
    },  
    function (error) {  
        if (error.response && error.response.status === 401) {  
            localStorage.removeItem("token");  
            localStorage.removeItem("username");  
            showToast("请重新登录");  
  
            setTimeout(function () {  
                location.href = "./login.html";  
            }, 1500);  
        }  
        return Promise.reject(error);  
    }  
);